package lq.auth.studyauth.configure;

import lq.auth.studyauth.properties.StudyAuthProperties;
import lq.auth.studyauth.properties.StudyClientsProperties;
import lq.auth.studyauth.service.StudyUserDetailService;
import lq.auth.studyauth.translator.StudyWebResponseExceptionTranslator;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 认证服务相关配置类
 *
 * @author LQ
 */
@Configuration
@EnableAuthorizationServer //开启认证服务器相关配置
public class StudyAuthorizationServerConfigure extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;
    @Autowired
    private StudyUserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private StudyAuthProperties authProperties;
    @Autowired
    private StudyWebResponseExceptionTranslator exceptionTranslator;

    /**
     * 客户端从认证服务器获取令牌的时候，
     * 必须使用client_id为study，client_secret为123456的标识来获取；
     * 该client_id支持password模式获取令牌，并且可以通过refresh_token来获取新的令牌；
     * 在获取client_id为febs的令牌的时候，scope只能指定为all，否则将获取失败；
     * 如果需要指定多个client，可以继续使用withClient配置。
     *
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        StudyClientsProperties[] clientsArray = authProperties.getClients();
        InMemoryClientDetailsServiceBuilder builder = clients.inMemory();
        if (ArrayUtils.isNotEmpty(clientsArray)) {
            for (StudyClientsProperties client : clientsArray) {
                if (StringUtils.isBlank(client.getClient())) {
                    throw new Exception("clent不能为空");
                }
                if (StringUtils.isBlank(client.getSecret())) {
                    throw new Exception("secret不能为空");
                }
                String[] grantTypes = StringUtils.splitByWholeSeparatorPreserveAllTokens(client.getGrantType(), ",");
                // 使用获取配置的方式替换了下面注释的硬编码
                builder.withClient(client.getClient()).secret(passwordEncoder.encode(client.getSecret())).authorizedGrantTypes(grantTypes).scopes(client.getScope());
            }
        }

        // clients.inMemory().withClient("study").secret(passwordEncoder.encode("123456")).authorizedGrantTypes("password", "refresh_token").scopes("all");
    }

    /**
     * 配置了认证异常翻译器后,需要使用exceptionTranslator(exceptionTranslator)进行异常的处理和使用
     * @SuppressWarnings("all")注解对警告保持静默
     * @param endpoints
     */
    @SuppressWarnings("all")
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenStore(tokenStore()).userDetailsService(userDetailService).authenticationManager(authenticationManager).tokenServices(defaultTokenServices()).exceptionTranslator(exceptionTranslator);
    }

    @Bean
    public TokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    /**
     * 指定令牌的基本配置，
     * 比如令牌有效时间为60 * 60 * 24秒，
     * 刷新令牌有效时间为60 * 60 * 24 * 7秒，
     * setSupportRefreshToken设置为true表示开启刷新令牌的支持。
     *
     * @return
     */
    @Primary
    @Bean
    public DefaultTokenServices defaultTokenServices() {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore());
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setAccessTokenValiditySeconds(authProperties.getAccessTokenValiditySeconds());
        tokenServices.setRefreshTokenValiditySeconds(authProperties.getRefreshTokenValiditySeconds());
//        tokenServices.setAccessTokenValiditySeconds(60 * 60 * 24);
//        tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);
        return tokenServices;
    }

}
